package com.gwt.boot.exception;

import com.gwt.cloud.constant.ApiResultEnum;
import com.gwt.cloud.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@ControllerAdvice
@Slf4j
public class BusinessExceptionHandler {

    /**
     * 默认异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult<Object> exceptionHandler(Exception e) {
        log.error (e.getMessage (), e);
        return new ApiResult<>(ApiResultEnum.FAIL.getStatus(), e.getMessage());
    }

    /**
     * 自定义业务异常处理
     * @param e BusinessException
     * @return ApiResponse
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ApiResult<Object> businessExceptionHandler(BusinessException e) {
        log.error (e.getMessage (), e);
        return new ApiResult<>(e.getStatus(), e.getMessage());
    }

    /**
     * 入参异常处理
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResult<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage = ApiResultEnum.FAIL_PARAMS.getMessage();
        if (bindingResult.getFieldError() != null){
            errorMessage = bindingResult.getFieldError().getDefaultMessage();
        }
        return new ApiResult<>(ApiResultEnum.FAIL_PARAMS.getStatus(), errorMessage);
    }

    /**
     * 入参类型异常处理
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public ApiResult<Object> httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e) {
        log.error (e.getMessage(), e);
        return new ApiResult<>(ApiResultEnum.FAIL_PARAMS_TYPE.getStatus(), ApiResultEnum.FAIL_PARAMS_TYPE.getMessage());
    }

    /**
     * 文件大小限制
     */
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    @ResponseBody
    public ApiResult<Object> argumentErrorHandler(MaxUploadSizeExceededException e) {
        log.error (e.getMessage(), e);
        return new ApiResult<>(ApiResultEnum.MAX_FILE_SIZE.getStatus(), ApiResultEnum.MAX_FILE_SIZE.getMessage());
    }
}
